package com.aispeech.astools.view;

import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import com.aispeech.astools.R;
import com.aispeech.astools.recorder.RecordListener;
import com.aispeech.astools.recorder.SerialRecord;
import com.aispeech.astools.utils.AudioFileWrite;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

public class SerialActivity extends AppCompatActivity implements OnClickListener {

    private final static String TAG = "SerialActivity";

    private String mSerialPortPath = "/dev/ttyS4";
    private int mBaudRate = 115200;

    private SerialRecord mSrd;

    private List<String> mDataList = new ArrayList<>();

    private BaseAdapter mDataAdapter;

    private EditText mEtSerialDevName, mEtSend;
    private Button mBtnOpen, mBtnSend;
    private Spinner mSpBaudrate;
    private ListView mLvIOData;

    private AudioFileWrite mAudioFile;
    private final String externalStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath();
    private final String AudioFilePath = externalStorageDirectory + File.separator + "aispeech" + File.separator + "serial.pcm";

    @Override
    public void onClick(View v) {
        if (v == mBtnOpen) {
            mSerialPortPath = mEtSerialDevName.getText().toString().trim();
            if (TextUtils.isEmpty(mSerialPortPath)) {
                showIOData("please input valid port name", "err");
                return;
            }

            if (mBaudRate <= 0) {
                showIOData("please select valid baudrate", "err");
                return;
            }

            mSrd.start(mSerialPortPath, mBaudRate);

            mBtnOpen.setEnabled(false);
        } else if (v == mBtnSend) {
            String sendData = mEtSend.getText().toString().trim();
            if (!TextUtils.isEmpty(sendData)) {
                mSrd.sendData(sendData);
                showIOData(sendData, "send");
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serial);
        mAudioFile = new AudioFileWrite(getApplication());
        mAudioFile.startWrite(AudioFilePath);

        initView();
        initSerialRecord();
    }

    private void initSerialRecord() {
        mSrd = new SerialRecord();
        mSrd.init(getApplication(), new RecordListener() {
            @Override
            public void onBuffer(byte[] data) {
                mAudioFile.writeBuffer(data);
            }

            @Override
            public void onEvent(EVENT event) {

            }

            @Override
            public void onError(String info) {
                showIOData(info, "err");
            }
        });
    }

    private void initView() {
        mEtSerialDevName = findViewById(R.id.et_serial_port_name);
        mEtSend = findViewById(R.id.et_send);

        mBtnOpen = findViewById(R.id.btn_open);
        mBtnOpen.setOnClickListener(this);
        mBtnOpen.requestFocus();

        mBtnSend = findViewById(R.id.btn_send);
        mBtnSend.setOnClickListener(this);

        mSpBaudrate = findViewById(R.id.sp_baudrate);
        mSpBaudrate.setSelection(11);

//        String[] barray = getResources().getStringArray(R.array.baudrate_array);
//        for (int i = 0; i < barray.length; i++) {
//            Log.d(TAG, "intArray[" + i + "]" + " = " + barray[i]);
//        }

        mSpBaudrate.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mBaudRate = Integer.parseInt(getResources().getStringArray(R.array.baudrate_array)[position]);
                Log.d(TAG, "onItemSelected with: position = " + position + ", mBaudRate = " + mBaudRate);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mLvIOData = findViewById(R.id.lv_io_data);
        mDataAdapter = new LvAdapter();
        mLvIOData.setAdapter(mDataAdapter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != mSrd) {
            mSrd.destroy();
        }

        if (null != mAudioFile) {
            mAudioFile.closeWrite();
        }
    }

    private void showIOData(final String data, final String type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDataList.add(type + " : " + data);
                mDataAdapter.notifyDataSetChanged();
                mLvIOData.setSelection(mDataList.size() - 1);
            }
        });
    }

    private class LvAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mDataList == null ? 0 : mDataList.size();
        }

        @Override
        public Object getItem(int i) {
            if (null != mDataList) {
                mDataList.get(i);
            }
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = SerialActivity.this.getLayoutInflater().inflate(R.layout.lv_info_item, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.tvInfo.setText(mDataList.get(i));
            return convertView;
        }
    }

    private final class ViewHolder {

        TextView tvInfo;

        ViewHolder(View view) {
            tvInfo = view.findViewById(R.id.tv_info);
        }
    }
    
}
